package cn.codeim;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {

    public void connect(int port, String host) {
        //客户端处理IO事件的线程组
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        //客户端辅助启动类
        Bootstrap bootstrap = new Bootstrap();
        try {
            Bootstrap channel = bootstrap.group(nioEventLoopGroup).channel(NioSocketChannel.class)//设置channel为NioSocketChannel
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() { //匿名内部类的方式，实现一个init方法
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new TimeClientHandler());
                        }
                    });

            //发起异步连接操作，等待连接
            ChannelFuture sync = bootstrap.connect(host, port).sync();

            //等待客户端链路关闭，异步阻塞
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //优雅退出，关闭NIO线程
            nioEventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = 8080;
        if(args!=null && args.length>0){
            try{
                port = Integer.parseInt(args[0]);
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        new TimeClient().connect(port, "127.0.0.1");
    }
}
